package com.codefish.codefish_blog.controller;

import com.codefish.codefish_blog.entity.BlogFile;
import com.codefish.codefish_blog.service.BlogFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;

/**
 * 博客文件controller类
 *
 * @author codefish
 * @version 1.0
 * @date 2022/03/29 下午 08:39
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    BlogFileService blogFileService;

    /**
     * 获取文件
     *
     * @param fileId   文件id
     * @param response response对象
     */
    @GetMapping("/{fileId}")
    @ResponseBody
    public void getFile(@PathVariable("fileId") Long fileId, ServletResponse response) {
        //设定对象头为图片(一般获取图片)
        response.setContentType("image/jpeg");
        BlogFile file = blogFileService.getById(fileId);
        //file对象为空，直接返回
        if (file == null) {
            return;
        }
        //获取图片二进制流，并由response输出
        byte[] data = file.getFileData();
        try (OutputStream os = response.getOutputStream()) {
            os.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
